//
//  HMComposeViewController.swift
//  MicroBlog
//
//  Created by Apple on 16/9/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
class HMComposeViewController: UIViewController {
    
    //懒加载
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 35, height: 35)
        button.addTarget(self, action: #selector(btnSendAction), for: .touchUpInside)
        return button
    }()
    
    //标题
    private lazy var titleLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGray, fontSIze: 16)
        if let name = HMUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name {
            //通过富文本设置attributedText属性
            let result = "发微博\n" + name
            //获取指定内容范围
            let range = (result as NSString).range(of: name)
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: result)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName: UIColor.magenta], range: range)
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    //输入文本框
    fileprivate lazy var textView: HMComposeTextView = {
       let view = HMComposeTextView()
        view.placeHolder = "啦啦啦~啦啦啦~啦啦啦~啦啦啦~我是卖报的小行家,啦啦啦~啦啦啦~啦啦啦~啦啦啦~我是卖报的小行家,啦啦啦~啦啦啦~啦啦啦~啦啦啦~我是卖报的小行家,啦啦啦~啦啦啦~啦啦啦~啦啦啦~我是卖报的小行家"
        view.font = UIFont.systemFont(ofSize: 15)
        view.delegate = self
        //垂直方向的弹簧效果
        view.alwaysBounceVertical = true
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //toolBar
    fileprivate lazy var toolBar: HMComposeToolBar = {
       let view = HMComposeToolBar()
        return view
    }()
    //配图
    fileprivate lazy var pictureView: HMComposeViewPictureView = {
       let view = HMComposeViewPictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    
    //表情键盘
    fileprivate lazy var emoticonKeyBoard: HMEmoticonKeyBoard = {
       let view = HMEmoticonKeyBoard()
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    //添加控件,设置约束
    private func setupUI() {
        //监听键盘的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(DidSelectedEmoticon(noti:)), name:  NSNotification.Name(DidSelectedEmoticonNotification), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(DidSelectedDeleteEmoticon), name: NSNotification.Name(DidSelectedDeleteEmoticonNotification), object: nil)
        
        setupNaviUI()
        
        view.addSubview(textView)
        view.addSubview (toolBar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.trailing.equalTo(textView)
            make.height.equalTo(35)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        toolBar.callBack = { [weak self] (type: HMComposeToolBarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self!.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emotion:
                print("表情")
                self?.didSelectedEmoticon()
            case .add:
                print("加号")
            }
        }
        //打开图片浏览器的闭包
        pictureView.lastCellCallBack = { [weak self] in
            //打开图片浏览器
            self?.didSelectedPicture()
        }
    }
    
    //点击事件
    @objc private func btnSendAction() {
        let accessToken = HMUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token
        let text = textView.emoticonText
        if pictureView.images.count > 0 {
            HMNetworkTools.sharedTools.upload(accessToken: accessToken!, status: text, image: pictureView.images.first!, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                //发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
                self.view.endEditing(true)
                self.dismiss(animated: true, completion: nil)

            })
        } else {
            SVProgressHUD.show()
            HMNetworkTools.sharedTools.update(accessToken: accessToken!, status: text) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "请求异常!")
                    return
                }
                //发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
                self.view.endEditing(true)
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
    
    private func setupNaviUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancleAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //设置按钮不可用状态
        navigationItem.rightBarButtonItem?.isEnabled = false
        navigationItem.titleView = titleLabel
    }
    
    //监听删除表情按钮的方法
    @objc private func DidSelectedDeleteEmoticon() {
        //删除内容
        textView.deleteBackward()
    }
    
    //监听表情按钮点击的方法
    @objc private func DidSelectedEmoticon(noti:Notification) {
        guard let emoticon = noti.object as? HMEmoticon else {
            return
        }
        textView.insertEmoticon(emoticon: emoticon)
        //每点击一个表情,保存到最近表情数组里
        HMEmoticonTools.shareTools.saveRecentEmoticonArray(emoticon: emoticon)
        //通知表情视图刷新数据
        emoticonKeyBoard.reloadRecentData()
    }
    
    //键盘frame改变通知
    @objc private func keyBoardFrameChange(noti:Notification) {
        //键盘完全弹出时的frame
        let keyBoardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).cgRectValue
        //键盘动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        //更新约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        //执行约束动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func cancleAction() {
        //textView失去第一响应者
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }

}

extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //有内容才可点击
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    //监听拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //textView失去第一响应者
        self.view.endEditing(true)
    }
}
//处理toolBar按钮点击逻辑
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    //处理点击表情逻辑
    func didSelectedEmoticon() {
        //设置自定义视图
        if textView.inputView == nil {
            //从系统键盘进入发哦表情键盘
            textView.inputView = emoticonKeyBoard
            //表示表情键盘
            toolBar.showIcon(isEmoticon: true)
        } else {
            //从表情键盘进入到系统键盘
            textView.inputView = nil
            //表示系统键盘
            toolBar.showIcon(isEmoticon: false)
        }
        //第一响应者
        textView.becomeFirstResponder()
        //刷新inputView
        textView.reloadInputViews()
    }
    
    //处理点击图片的逻辑
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        //设置代理
        imagePictureCtr.delegate = self
        //是否支持传入的来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            imagePictureCtr.sourceType = .camera
        } else {
            imagePictureCtr.sourceType = .photoLibrary
        }
        //判断是否支持前置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            
        }
        //后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            
        }
        //允许编辑
//        imagePictureCtr.allowsEditing = true
        self.present(imagePictureCtr, animated: true, completion: nil)
    }
    
    //UIImagePickerControllerDelegate
    //取消
//    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//        dismiss(animated: true, completion: nil)
//    }
    
    //选中图片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info["UIImagePickerControllerOriginalImage"]! as! UIImage
        
        let scaleImage = image.scaleImage(scaleWidth: 200)
        print(image)
        pictureView.addImage(image: scaleImage)
        picker.dismiss(animated: true, completion: nil)
    }
}
